package com.chookss.home.search.fragment;


import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.search.adapter.SearchGonggaoAdapter;
import com.chookss.home.search.entity.SearchAllEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.RecycleViewDivider;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.annotations.NonNull;

@SuppressLint("ValidFragment")
public class SearchGonggaoFragment extends SearchBaseFragment {

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.rvView)
    RecyclerView rv;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    private SearchGonggaoAdapter adapter;
    private List<SearchAllEntity.NoticeBean.ListBean> list = new ArrayList<>();
    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    private String localKey="",localType="0";
    public SearchGonggaoFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search_base, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void onViewStateRestored(@androidx.annotation.Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
    }

    private void init() {
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rv.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5f), getResources().getColor(R.color.line_gray)));
        adapter = new SearchGonggaoAdapter(R.layout.item_search_gonggao_list, mContext, list);
        rv.setAdapter(adapter);
        rv.getItemAnimator().setAddDuration(0);
        rv.getItemAnimator().setChangeDuration(0);
        rv.getItemAnimator().setMoveDuration(0);
        rv.getItemAnimator().setRemoveDuration(0);
        ((SimpleItemAnimator) rv.getItemAnimator()).setSupportsChangeAnimations(false);
        rv.setItemAnimator(null);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
                srlView.setEnableRefresh(false);
            }
        });
    }

    @Override
    public void onVisible() {
        super.onVisible();
        if(srlView==null){
            return;
        }
        if(Utils.isNull(localKey)){
            srlView.autoRefresh();
        }else{
            if(localKey.equals(key)&&localType.equals(searchType)){
            }else{
                srlView.setEnableRefresh(true);
                srlView.autoRefresh();
            }
        }
    }
    @Override
    public void refreshData() {
        if(srlView==null){
            return;
        }
        srlView.setEnableRefresh(true);
        srlView.autoRefresh();
    }
    private void getData() {
        localKey=key;
        localType=searchType;
        adapter.setKey(localKey);
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("word", key);
        map.put("searchType", searchType);
        map.put("itemType", "notice");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<SearchAllEntity>>() {
        }.getType(), null, Urls.selectForSearch, SignUtils2.makeSignStr(map), false, new ObserverCallback<SearchAllEntity>() {
            @Override
            public void onSuccess(SearchAllEntity data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                loadEnd();
                if(srlView==null||llNone==null){
                    return;
                }
                if(data.getNotice()==null){
                    isEnd = true;
                    if (list.size() == 0) {

                        srlView.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                        String init = "抱歉，没用找到关于“<font color='#666666'>"+key+"</font>”的公告";
                        tvNone.setText(Html.fromHtml(init));
                    }
                    return;
                }
                if (data.getNotice().getList() != null && data.getNotice().getList().size() > 0) {
                    list.addAll(data.getNotice().getList());
                    adapter.notifyDataSetChanged();
                    srlView.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        srlView.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                        String init = "抱歉，没用找到关于“<font color='#666666'>"+key+"</font>”的公告";
                        tvNone.setText(Html.fromHtml(init));
                    }
                }

            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @Override
    public void initImmersionBar() {

    }
    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
